package shuashuami.hb.com.fragment.bussiness;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import shuashuami.hb.com.adapter.CdistriutionCenterAadpter;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.http.HttpBMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.http.LoginHttp;
import shuashuami.hb.com.model.CdistriutionCenter;
import shuashuami.hb.com.share.ShareCUserInfo;
import shuashuami.hb.com.util.LoadType;
import shuashuami.hb.com.view.pull.PullToRefreshLayout;

/**
 * A simple {@link Fragment} subclass.
 */
public class BdistributionFragment extends Fragment {

    private ListView listView;

    private CdistriutionCenterAadpter adatper;
    private List<CdistriutionCenter> mResources;

    private String type;

    private int size = 10;
    private int maxpage=-1;
    private PullToRefreshLayout mptrl;
    private int page = 1;

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cdistribution, container, false);
        initView(view);
        initData();
        initListener();

        return view;
    }

    private void initView(View view) {
        listView = (ListView) view.findViewById(R.id.lv_listview);
        mptrl= (PullToRefreshLayout) view.findViewById(R.id.refresh_view);
    }

    protected void initData() {
        mResources=new ArrayList<>();
        adatper=new CdistriutionCenterAadpter(mResources,getActivity());
        listView.setAdapter(adatper);
        getMessage();
    }

    public int operateType = LoadType.NO_OPERATE;

    protected void initListener() {
        mptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {


            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                //
                operateType= LoadType.DO_REFERSH;
                page=1;
                getMessage();

            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                if(maxpage==-1 || page==maxpage){
                    mptrl.loadmoreFinish(PullToRefreshLayout.NODATA);
                    return;
                }
//
                operateType= LoadType.LOAD_MORE;
                page++;
                getMessage();
            }
        });
    }

    private void initAdapter( List<CdistriutionCenter> list) {


        // 如果是刷新
        if(operateType== LoadType.DO_REFERSH){
            mResources.clear();
        }


        mResources.addAll(list);

        adatper.notifyDataSetChanged();
        if(operateType== LoadType.DO_REFERSH){
            mptrl.refreshFinish(PullToRefreshLayout.SUCCEED);
        }
        if(operateType== LoadType.LOAD_MORE){
            mptrl.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        }

        operateType= LoadType.NO_OPERATE;

    }

    private void getMessage() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(getActivity());
        HttpBMethods.distributionCenter(listener, type,
                shareCUserInfo.getId(), page + "", "10"
        );
    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    try {
                        List<CdistriutionCenter> list = new ArrayList<>();
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(getActivity());
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            JSONObject t = jsonObject.getJSONObject("content");
                            JSONArray jsonArray = t.getJSONArray("list");
                            page= t.getInt("currentpage");
                            maxpage=t.getInt("maxpage");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                try {
                                    JSONObject temp = jsonArray.getJSONObject(i);
                                    CdistriutionCenter cdistriutionCenter = new CdistriutionCenter(temp.getString("avatar"),
                                            temp.getString("id"), temp.getString("username"), temp.getString("mobile"), temp.getString("addtime"), temp.getString("commission_shop_parent"));
                                    list.add(cdistriutionCenter);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            ToastUtil.showShort(getActivity(), jsonObject.getString("message"));
                        }

                        initAdapter(list);

                    } catch (JSONException e) {
                        ToastUtil.showShort(getActivity(), "数据解析错误");
                    }


                    break;
            }

            super.handleMessage(msg);
        }
    };
}
